import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Input, Drawer, Table } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  ModalForm,
  ProFormDigit,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-form';
import type { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import ProDescriptions from '@ant-design/pro-descriptions';
import type { FormValueType } from './components/UpdateForm';
import UpdateForm from './components/UpdateForm';
import { rule, addRule, updateRule, removeRule, addVideoRecord } from './service';
import type { TableListItem, TableListPagination, VideoRecord } from './data';
import VideoColumn, { IVideoRecordChart } from './components/VideoColumn';

/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields: TableListItem) => {
  const hide = message.loading('正在添加');

  try {
    const result = await addRule({ ...fields });
    console.log('rs', result);
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

const handleAddRecord = async (fields: VideoRecord & { videoId: number }) => {
  const hide = message.loading('正在添加');

  try {
    const result = await addVideoRecord({ ...fields });
    console.log('rs', result);
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 *
 * @param fields
 */

const handleUpdate = async (fields: FormValueType, currentRow?: TableListItem) => {
  const hide = message.loading('正在配置');

  try {
    await updateRule({
      ...currentRow,
      ...fields,
    });
    hide();
    message.success('配置成功');
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows: TableListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeRule({
      key: selectedRows.map((row) => row.id),
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const platformToString = (platform?: number) => {
  if (platform == 0) return '抖音';
  return '头条';
};

const durationToString = (duration?: number) => {
  if (duration == 0) return '一日内';
  else if (duration == 1) return '三日内';
  else if (duration == 2) return '一周内';
  else if (duration == 3) return '半月内';
  return '一月内';
};

const TableList: React.FC = () => {
  /** 新建窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [addRecordModalVisible, handleAddRecordModalVisible] = useState<boolean>(false);
  const [selectedVideoId, setSelectedVideoId] = useState(0);
  const [recordCharts, setRecordCharts] = useState<IVideoRecordChart[]>([]);
  /** 分布更新窗口的弹窗 */
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<TableListItem>();
  const [selectedRowsState, setSelectedRows] = useState<TableListItem[]>([]);

  const computedVideoRecords = (item: TableListItem) => {
    const records = item.records;
    const result: IVideoRecordShow[] = [];
    const d = records?.filter((it) => it.platform == 0);
    if (d?.length) {
      const dPlatform: IVideoRecordShow = {
        platform: d[0].platform,
        harf: d[0].harf,
        oneDayViews: 0,
        oneDayLikes: 0,
        oneDayComments: 0,
        oneDayCollections: 0,
        threeDayViews: 0,
        threeDayLikes: 0,
        threeDayComments: 0,
        threeDayCollections: 0,
        weekDayViews: 0,
        weekDayLikes: 0,
        weekDayComments: 0,
        weekDayCollections: 0,
      };
      for (const i of d) {
        // 一日内
        if (i.type == 0) {
          dPlatform.oneDayViews = i.views;
          dPlatform.oneDayLikes = i.likes;
          dPlatform.oneDayComments = i.comments;
          dPlatform.oneDayCollections = i.collections;
        } else if (i.type == 1) {
          dPlatform.threeDayViews = i.views;
          dPlatform.threeDayLikes = i.likes;
          dPlatform.threeDayComments = i.comments;
          dPlatform.threeDayCollections = i.collections;
        } else {
          dPlatform.weekDayViews = i.views;
          dPlatform.weekDayLikes = i.likes;
          dPlatform.weekDayComments = i.comments;
          dPlatform.weekDayCollections = i.collections;
        }
      }

      result.push(dPlatform);
    }

    const t = records?.filter((it) => it.platform == 1);

    if (t?.length) {
      const tPlatform: IVideoRecordShow = {
        platform: t[0].platform,
        harf: t[0].harf,
        oneDayViews: 0,
        oneDayLikes: 0,
        oneDayComments: 0,
        oneDayCollections: 0,
        threeDayViews: 0,
        threeDayLikes: 0,
        threeDayComments: 0,
        threeDayCollections: 0,
        weekDayViews: 0,
        weekDayLikes: 0,
        weekDayComments: 0,
        weekDayCollections: 0,
      };
      for (const i of t) {
        // 一日内
        if (i.type == 0) {
          tPlatform.oneDayViews = i.views;
          tPlatform.oneDayLikes = i.likes;
          tPlatform.oneDayComments = i.comments;
          tPlatform.oneDayCollections = i.collections;
        } else if (i.type == 1) {
          tPlatform.threeDayViews = i.views;
          tPlatform.threeDayLikes = i.likes;
          tPlatform.threeDayComments = i.comments;
          tPlatform.threeDayCollections = i.collections;
        } else {
          tPlatform.weekDayViews = i.views;
          tPlatform.weekDayLikes = i.likes;
          tPlatform.weekDayComments = i.comments;
          tPlatform.weekDayCollections = i.collections;
        }
      }

      result.push(tPlatform);
    }

    return result;
  };

  const computedVideoRecordChart = (item: TableListItem): IVideoRecordChart[] => {
    const records = item.records || [];
    const charts: IVideoRecordChart[] = [];

    let maxType = 0;

    records.forEach((record) => {
      const title = platformToString(record.platform);
      const type = durationToString(record.type);

      maxType = Math.max(maxType, record.type || 0);

      charts.push({ title, type, field: '浏览量', value: record.views || 0 });
      charts.push({ title, type, field: '点赞', value: record.likes || 0 });
      charts.push({ title, type, field: '评论', value: record.comments || 0 });
      charts.push({ title, type, field: '收藏', value: record.collections || 0 });
    });

    for (let i = maxType + 1; i < 5; i++) {
      const type = durationToString(i);
      for (let j = 0; j < 2; j++) {
        const title = platformToString(j);

        charts.push({ title, type, field: '浏览量', value: 0 });
        charts.push({ title, type, field: '点赞', value: 0 });
        charts.push({ title, type, field: '评论', value: 0 });
        charts.push({ title, type, field: '收藏', value: 0 });
      }
    }

    return charts;
  };

  /** 国际化配置 */

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '名称',
      dataIndex: 'title',
      tip: '名称是唯一的 key',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              const charts = computedVideoRecordChart(entity);
              setRecordCharts(charts);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },

    {
      title: '浏览量',
      dataIndex: 'views',
      sorter: true,
      hideInForm: true,
      renderText(text, record, index, action) {
        const records = record.records || [];
        const p1 = records
          .filter((item) => item.platform == 0)
          .sort((a, b) => (a.type || 0) - (b.type || 0));
        const max1 = p1[0];
        const p2 = records
          .filter((item) => item.platform == 1)
          .sort((a, b) => (a.type || 0) - (b.type || 0));
        const max2 = p2[0];
        const views = (max1?.views || 0) + (max2?.views || 0);
        return views;
      },
    },
    {
      title: '点赞',
      dataIndex: 'likes',
      sorter: true,
      hideInForm: true,
      renderText(text, record, index, action) {
        const records = record.records || [];
        const p1 = records
          .filter((item) => item.platform == 0)
          .sort((a, b) => (a.type || 0) - (b.type || 0));
        const max1 = p1[0];
        const p2 = records
          .filter((item) => item.platform == 1)
          .sort((a, b) => (a.type || 0) - (b.type || 0));
        const max2 = p2[0];
        const likes = (max1?.likes || 0) + (max2?.likes || 0);
        return likes;
      },
    },
    {
      title: '评论',
      dataIndex: 'comments',
      sorter: true,
      hideInForm: true,
      renderText(text, record, index, action) {
        const records = record.records || [];
        const p1 = records
          .filter((item) => item.platform == 0)
          .sort((a, b) => (a.type || 0) - (b.type || 0));
        const max1 = p1[0];
        const p2 = records
          .filter((item) => item.platform == 1)
          .sort((a, b) => (a.type || 0) - (b.type || 0));
        const max2 = p2[0];
        const comments = (max1?.comments || 0) + (max2?.comments || 0);
        return comments;
      },
    },

    {
      title: '收藏',
      dataIndex: 'collections',
      sorter: true,
      hideInForm: true,
      renderText(text, record, index, action) {
        const records = record.records || [];
        const p1 = records
          .filter((item) => item.platform == 0)
          .sort((a, b) => (a.type || 0) - (b.type || 0));
        const max1 = p1[0];
        const p2 = records
          .filter((item) => item.platform == 1)
          .sort((a, b) => (a.type || 0) - (b.type || 0));
        const max2 = p2[0];
        const collections = (max1?.collections || 0) + (max2?.collections || 0);
        return collections;
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: {
        0: {
          text: '草稿',
          status: 'Default',
        },
        1: {
          text: '公开',
          status: 'Processing',
        },
        2: {
          text: '私密',
          status: 'Success',
        },
        3: {
          text: '已删除',
          status: 'Error',
        },
      },
    },
    {
      title: '统计截止时间',
      sorter: true,
      dataIndex: 'updatedAt',
      valueType: 'dateTime',
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return defaultRender(item);
      },
    },
    {
      title: '总结',
      dataIndex: 'summary',
      valueType: 'textarea',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            handleUpdateModalVisible(true);
            setCurrentRow(record);
          }}
        >
          配置
        </a>,
        <a
          key="addRecord"
          onClick={() => {
            setSelectedVideoId(record.id);
            handleAddRecordModalVisible(true);
            //  handleUpdateModalVisible(true);
            //  setCurrentRow(record);
          }}
        >
          添加记录
        </a>,
        <a key="subscribeAlert" href="https://procomponents.ant.design/">
          订阅警报
        </a>,
      ],
    },
  ];

  const videoColumns: ProColumns<VideoRecord>[] = [
    {
      title: '平台',
      dataIndex: 'platform',
      search: false,
      valueEnum: {
        0: {
          text: '抖音',
          status: 'Default',
        },
        1: {
          text: '头条',
          status: 'Processing',
        },
      },
    },
    {
      title: '视频链接',
      dataIndex: 'harf',
      search: false,
      render: (dom, entity) => {
        return (
          <a href={entity.harf} target="_blank" rel="noreferrer">
            {entity.harf}
          </a>
        );
      },
    },
    {
      title: '浏览量',
      dataIndex: 'views',
      valueType: 'textarea',
    },
    {
      title: '点赞',
      dataIndex: 'likes',
      valueType: 'textarea',
    },
    {
      title: '评论',
      dataIndex: 'comments',
      valueType: 'textarea',
    },
    {
      title: '收藏',
      dataIndex: 'collection',
      valueType: 'textarea',
    },
    {
      title: '日期区间',
      dataIndex: 'type',
      valueEnum: {
        0: {
          text: '一日内',
          status: 'Default',
        },
        1: {
          text: '三日内',
          status: 'Processing',
        },

        2: {
          text: '一周内',
          status: 'Processing',
        },

        3: {
          text: '半月内',
          status: 'Processing',
        },

        4: {
          text: '一月内',
          status: 'Processing',
        },
      },
    },
  ];

  return (
    <PageContainer>
      <ProTable<TableListItem, TableListPagination>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建信息
          </Button>,
        ]}
        request={rule}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
              <span>
                服务调用次数总计 {selectedRowsState.reduce((pre, item) => pre + item.callNo!, 0)} 万
              </span>
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
          <Button type="primary">批量审批</Button>
        </FooterToolbar>
      )}
      <ModalForm
        title="新建信息"
        width="400px"
        visible={createModalVisible}
        onVisibleChange={handleModalVisible}
        onFinish={async (value) => {
          const success = await handleAdd(value as TableListItem);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText
          rules={[
            {
              required: true,
              message: '名称必填',
            },
          ]}
          width="md"
          label='名称'
          name="title"
        />
        <ProFormTextArea width="md" name="summary" label="总结" />
        <ProFormSelect
          name="status"
          label='状态'
          options={[
            {
              label: '草稿',
              value: 0,
            },
            {
              label: '公开',
              value: 1,
            },
            {
              label: '私密',
              value: 2,
            },
            {
              label: '已删除',
              value: 3,
            },
          ]}
        />
      </ModalForm>

      <ModalForm
        title="添加记录"
        width="400px"
        visible={addRecordModalVisible}
        onVisibleChange={handleAddRecordModalVisible}
        onFinish={async (value) => {
          const success = await handleAddRecord({
            ...value,
            videoId: selectedVideoId,
          } as VideoRecord & { videoId: number });
          if (success) {
            handleAddRecordModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormSelect
          name="platform"
          label="平台"
          options={[
            {
              label: '抖音',
              value: 0,
            },
            {
              label: '头条',
              value: 1,
            },
          ]}
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: '链接地址必填',
            },
          ]}
          width="md"
          name="harf"
          label="链接地址"
        />
        <ProFormDigit name="views" label="浏览量" />
        <ProFormDigit name="likes" label="点赞数" />
        <ProFormDigit name="comments" label="评论数" />
        <ProFormDigit name="collections" label="收藏数" />
        <ProFormSelect
          name="type"
          label="日期区间"
          options={[
            {
              label: '一日内',
              value: 0,
            },
            {
              label: '三日内',
              value: 1,
            },
            {
              label: '一周内',
              value: 2,
            },
            {
              label: '半月内',
              value: 3,
            },

            {
              label: '一月内',
              value: 4,
            },
          ]}
        />
      </ModalForm>
      <UpdateForm
        onSubmit={async (value) => {
          const success = await handleUpdate(value, currentRow);

          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);

            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          setCurrentRow(undefined);
        }}
        updateModalVisible={updateModalVisible}
        values={currentRow || {}}
      />

      <Drawer
        width={1000}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.title && (
          <>
            <ProDescriptions<TableListItem>
              column={2}
              title={currentRow?.title}
              request={async () => ({
                data: currentRow || {},
              })}
              params={{
                id: currentRow?.title,
              }}
              columns={columns as ProDescriptionsItemProps<TableListItem>[]}
            />
            <ProTable<VideoRecord>
              rowKey="key"
              search={false}
              dataSource={currentRow.records || []}
              columns={videoColumns}
            />
            <div style={{ padding: '0px 30px' }}>
              <VideoColumn data={recordCharts}></VideoColumn>
            </div>
          </>
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
